package com.lyf.shop.web.filter;

import com.lyf.shop.common.Const;
import com.lyf.shop.entity.User;
import com.lyf.shop.services.Impl.UserServiceImpl;
import com.lyf.shop.services.UserService;
import com.lyf.shop.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "Filter_AutoLogin02",value = "/login.jsp")
public class Filter_AutoLogin02 implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //1检查cookie
        Cookie[] cookies = request.getCookies();
        String value = null;
        for(Cookie cookie: cookies){
            //直接进行name值的对比
            if (cookie.getName().equals(Const.UserConst.AUTO_LOGIN)){
                //用户有设置自动登录，并且已有登录成功
                value=cookie.getValue();//获取的是加密过用户名和密码的拼接字符串
            }
        }
        if(value!=null){
            //解码==》用户名：密码
            String[] split = Base64Utils.decode(value).split(Const.COLON);
            String uname = split[0];
            String upassword = split[1];
            //再次进行用户名和密码的验证，防止用户在其他地方已经有修改过密码

            UserService userService = new UserServiceImpl();
            User user = userService.findUserByUname(uname);

            if (user.getUpassword().equals(upassword)){
                //用户名和密码没有变更，所以就直接帮用户进行登录
                request.getSession().setAttribute("login_user",user);
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }else {
                //直接放行到login.jsp
                chain.doFilter(request, response);
            }
        } else {
            //用户没有在cookie中保存信息，即自动登录没有设置或过期
            //直接放行到login.jsp
            chain.doFilter(request,response);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
